<template>
  <div class="edit-member-container">
    <!-- 顶部导航区域 -->
    <div class="header-wrapper">
      <!-- 顶部导航 -->
      <div class="header">
        <div class="header-back" @click="goBack">取消</div>
        <div class="header-title">员工信息</div>
        <div class="header-action"  v-if="isFromOrganization"  @click="handleComplete">完成</div>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <van-loading type="spinner" color="#1989fa">加载中...</van-loading>
    </div>

    <!-- 表单内容 -->
    <div v-else class="form-container">
      <!-- 员工姓名 -->
      <div class="form-item">
        <div class="form-label">姓名</div>
        <van-field
          v-model="memberName"
          placeholder="必填"
          :border="false"
          class="custom-field"
          autocomplete="off"
          readonly
        />
      </div>

      <!-- 手机号码 -->
      <div class="form-item">
        <div class="form-label">手机号码</div>
        <van-field
          type="tel"
          v-model="phone"
          placeholder="必填"
          :border="false"
          class="custom-field"
          autocomplete="off"
          readonly
        />
      </div>
    <!-- 从组织架构首页进入时显示角色选择 -->
    <template v-if="isFromOrganization">
      <div class="message_title">角色设置</div>
      
      <!-- 角色选择 -->
      <div class="form-item">
        <div class="form-label">角色</div>
        <van-field
          v-model="selectedRoleText"
          is-link
          readonly
          placeholder="请选择角色"
          :border="false"
          class="custom-field"
          @click="showRoleSelect = true"
        />
      </div>

    <!-- 角色选择弹窗 -->
    <van-popup v-model:show="showRoleSelect" round position="bottom">
      <van-picker
        title="选择角色"
        :columns="roleColumns"
        @cancel="showRoleSelect = false"
        @confirm="onRoleConfirm"
      />
    </van-popup>
    </template>
    
    <!-- 从部门页面进入时显示完整任职信息 -->
    <template v-else>
      <div class="message_title">任职信息</div>

      <!-- 部门 -->
      <div class="form-item job-info-item">
        <div class="form-label">部门</div>
        <div class="form-value">
          <span v-if="departmentName" class="selected-department">{{ departmentName }}</span>
          <span v-else class="placeholder">暂无部门信息</span>
        </div>
      </div>

      <!-- 职位 -->
      <div class="form-item job-info-item">
        <div class="form-label ">职位</div>
        <van-field
          v-model="position"
          placeholder="必填"
          :border="false"
          class="custom-field"
          autocomplete="off"
          readonly
        />
      </div>
      <!-- 入职时间 -->
      <div class="form-item job-info-item">
        <div class="form-label">入职时间</div>
        <div class="form-value">
          <span v-if="createDate" class="selected-date">{{ createDate }}</span>
          <span v-else class="placeholder">暂无入职时间</span>
        </div>
      </div>
    </template>

      <!-- 是否为主管 -->
      <!-- <div class="form-item">
        <div class="form-label">设为主管</div>
        <div class="form-value">
          <van-switch v-model="isManager" size="24px" />
        </div>
      </div> -->

      <!-- 编辑个人信息 -->
      <!-- <div class="form-item job-info-item" @click="editPersonalInfo">
        <div class="form-label">编辑个人信息</div>
        <div class="form-value">
          <van-icon name="arrow" class="arrow-icon" />
        </div>
      </div> -->
    </div>

    <!-- 底部操作按钮 - 只在从部门页面进入时显示 -->
    <div v-if="!isFromOrganization && isAdmin" class="bottom-actions">
      <div class="action-buttons">
        <div class="action-btn delete-btn" @click="handleDirectDelete">
          <span>直接删除员工</span>
        </div>
        <div class="action-btn resign-btn" @click="handleResignAndDelete">
          <span>办理离职并删除</span>
        </div>
      </div>
    </div>



    <!-- 删除确认弹窗 -->
    <van-dialog
      v-model:show="showDeleteDialog"
      title="确认删除"
      :message="deleteMessage"
      show-cancel-button
      :confirm-button-loading="deleteLoading"
      :cancel-button-disabled="deleteLoading"
      @confirm="confirmDelete"
      @cancel="showDeleteDialog = false"
    />
    

  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { showToast } from 'vant'
import { getUserById, type UserInfo } from '@/api/user'
import { getAllDepartments, removeMember, deleteMember, updateUser, type UpdateUserRequest } from '@/api/organization'
import { smartGoBack } from '@/utils/navigation';
import { storage } from '@/utils/storage';
// 路由实例
const router = useRouter()
const route = useRoute()

// 表单数据
const memberName = ref('')
const phone = ref('')
const position = ref('')
const isManager = ref(false)
const createDate = ref('')
const departmentName = ref('')
const loading = ref(false) // 初始为false，避免闪烁

// 弹窗控制
const showDeleteDialog = ref(false)
const deleteMessage = ref('')
const deleteType = ref('') // 'direct' 或 'resign'
const deleteLoading = ref(false)

// 员工信息
const memberInfo = ref<UserInfo | null>(null)
// 部门列表
const departments = ref<any[]>([])

// 当前登录用户信息
const currentUser = ref<any>(null);
// 当前用户详细信息（从接口获取）
const currentUserDetail = ref<any>(null);

// 计算属性：判断当前用户是否为管理员
const isAdmin = computed(() => {
  return currentUserDetail.value?.admin === 1;
});
// 获取当前登录用户信息
const getCurrentUserInfo = async () => {
  try {
    const userInfo = storage.getUserInfo();
    if (userInfo) {
      currentUser.value = userInfo;
      console.log('当前用户信息:', userInfo);
      
      // 调用接口获取用户详细信息
      const response = await getUserById(userInfo.id.toString());
      if (response.code === 0) {
        currentUserDetail.value = response.data;
        console.log('用户详细信息:', response.data);
        console.log('是否为管理员:', response.data.admin === 1);
      }
    }
  } catch (error) {
    console.error('获取用户信息失败:', error);
  }
};
// CEO/HR--换成出纳选择相关
const selectedRole = ref('')
const selectedRoleText = ref('')
const showRoleSelect = ref(false)
const roleOptions = [
  { text: 'CEO', value: 'ceo' },
  { text: '出纳', value: 'hr' }
]
// Vant 4 Picker组件的columns格式
const roleColumns = roleOptions.map(option => ({
  text: option.text,
  value: option.value
}))

// 角色选择确认 - Vant 4格式
const onRoleConfirm = ({ selectedOptions }: { selectedOptions: Array<{ text: string; value: string }> }) => {
  const selectedOption = selectedOptions[0]
  if (selectedOption) {
    selectedRole.value = selectedOption.value
    selectedRoleText.value = selectedOption.text
  }
  showRoleSelect.value = false
}

// 根据角色值获取显示文本
const getRoleText = (roleValue: string): string => {
  const option = roleOptions.find(opt => opt.value === roleValue)
  return option ? option.text : ''
}

// 判断是否从组织架构首页进入
const isFromOrganization = computed(() => {
  return route.query.from === 'organization'
})

// 返回上一页
const goBack = () => {
  smartGoBack(router)
}

// 获取部门名称
const getDepartmentName = (departmentId: number): string => {
  const department = departments.value.find(dept => dept.id === departmentId)
  return department ? department.name : '未知部门'
}

// 获取用户信息
const fetchUserInfo = async (userId: string) => {
  try {
    loading.value = true
    const response = await getUserById(userId)
    
    if (response.code === 0) {
      memberInfo.value = response.data
      
      // 填充表单数据
      memberName.value = response.data.name
      phone.value = response.data.phone
      position.value = response.data.position
      
      // 获取部门名称
      departmentName.value = getDepartmentName(response.data.department)
      createDate.value = response.data.createDate
      
      // 如果从组织架构首页进入，设置当前角色
      if (isFromOrganization.value) {
        if (response.data.ceo === 1) {
          selectedRole.value = 'ceo'
          selectedRoleText.value = getRoleText('ceo')
        } else if (response.data.hr === 1) {
          selectedRole.value = 'hr'
          selectedRoleText.value = getRoleText('hr')
        }
      }
      
      console.log('用户信息加载成功:', response.data)
    } else {
      showToast(response.msg || '获取用户信息失败')
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
    showToast('获取用户信息失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 获取部门列表
const fetchDepartments = async () => {
  try {
    const response = await getAllDepartments()
    if (response.code === 0) {
      departments.value = response.data.departments
    }
  } catch (error) {
    console.error('获取部门列表失败:', error)
  }
}

// 直接删除员工
const handleDirectDelete = () => {
  deleteType.value = 'direct'
  deleteMessage.value = `确认删除当前员工？`
  showDeleteDialog.value = true
}

// 办理离职并删除
const handleResignAndDelete = () => {
  deleteType.value = 'resign'
  deleteMessage.value = `确认当前员工已离职？`
  showDeleteDialog.value = true
}

// 确认删除
const confirmDelete = async () => {
  if (!memberInfo.value) {
    showToast('员工信息不存在')
    showDeleteDialog.value = false
    return
  }

  try {
    deleteLoading.value = true
    
    if (deleteType.value === 'direct') {
      // 直接删除员工 - 需要组织ID和员工ID
      // 这里使用部门ID作为组织ID，实际项目中可能需要调整
      const response = await removeMember(memberInfo.value.department, memberInfo.value.id)
      
      if (response.code === 0) {
        showToast('员工已删除')
        router.back()
      } else {
        showToast(response.msg || '删除失败')
      }
    } else {
      // 办理离职并删除
      const response = await deleteMember(memberInfo.value.id)
      
      if (response.code === 0) {
        showToast('离职手续已办理，员工已删除')
        router.back()
      } else {
        showToast(response.msg || '办理离职失败')
      }
    }
  } catch (error) {
    console.error('删除操作失败:', error)
    showToast('操作失败，请稍后重试')
  } finally {
    deleteLoading.value = false
    showDeleteDialog.value = false
  }
}



// 完成按钮处理
const handleComplete = async () => {
  if (!memberInfo.value) {
    showToast('用户信息不存在')
    return
  }
  
  // 如果从组织架构首页进入，调用updateUser接口
  if (isFromOrganization.value) {
    if (!selectedRole.value) {
      showToast('请选择角色')
      return
    }
    
    try {
      loading.value = true
      
      const updateData: UpdateUserRequest = {
        id: memberInfo.value.id,
        ceo: selectedRole.value === 'ceo' ? 1 : 0,
        hr: selectedRole.value === 'hr' ? 1 : 0
      }
      
      const response = await updateUser(updateData)
      
      if (response.code === 0) {
        showToast('更新成功')
        router.back()
      } else {
        showToast(response.msg || '更新失败')
      }
    } catch (error) {
      console.error('更新用户失败:', error)
      showToast('更新失败，请稍后重试')
    } finally {
      loading.value = false
    }
  } else {
    // 从部门页面进入，直接返回
    router.back()
  }
}

// 页面初始化
onMounted(async () => {
  // 获取员工ID
  const memberId = route.params.id as string
  
  if (!memberId) {
    showToast('员工ID不能为空')
    router.back()
    return
  }
  
  // 先获取部门列表，再获取用户信息
  await fetchDepartments()
  await fetchUserInfo(memberId)
  await getCurrentUserInfo(); // 获取当前用户信息
  console.log('编辑员工页面已加载', { memberId, memberInfo: memberInfo.value, isFromOrganization: isFromOrganization.value })
})
</script>

<style lang="scss" scoped>
@import url('./style/edit-member.scss');
</style>